package com.hnust.controller.subject;

import com.hnust.domain.*;
import com.hnust.fx.FXMLController;
import com.hnust.service.SubjectService;
import com.hnust.store.DataStore;
import com.hnust.store.SubjectStore;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Rectangle2D;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Screen;
import javafx.util.StringConverter;
import org.springframework.beans.factory.annotation.Autowired;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * 创建人：zhangRuWang
 * 创建时间：2020/12/8
 * 描述：
 */
@FXMLController
public class AddSubjectController implements Initializable {
    @FXML
    private TextField knowledgePoint;
    @FXML
    private TextArea subjectContent;
    @FXML
    private TextArea subjectResolve;
    @FXML
    private ComboBox<QuestionTypeRecord> comb1;
    @FXML
    private RadioButton r1;
    @FXML
    private RadioButton r2;
    @FXML
    private RadioButton r3;
    @FXML
    private ComboBox<CourseData> comb3;
    @FXML
    private ComboBox<CourseChapter> comb4;
    @FXML
    private ComboBox<CourseTargetRecord> comb5;
    @FXML
    private VBox falseVbox;
    private final List<TextArea> trueTextAreas=new ArrayList<>();
    @FXML
    private VBox trueVbox;
    private final List<TextArea> falseTextAreas=new ArrayList<>();
    @FXML
    private AnchorPane addSubjectWindow;
    @Autowired
    private SubjectStore subjectStore;
    @Autowired
    private DataStore dataStore;
    @Autowired
    private SubjectService subjectService;
    ObservableList<CourseData> com;
    ObservableList<CourseTargetRecord> courseTargetRecords;
    ObservableList<CourseChapter> courseChapters;
    ObservableList<QuestionTypeRecord> questionTypeRecords;
    private String selectCourseId;
    private String selectChapterId;
    private String selectTargetId;
    private Integer selectQueTypeId;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Screen s=Screen.getPrimary();
        Rectangle2D visualBound=s.getVisualBounds();
        addSubjectWindow.setPrefHeight(visualBound.getHeight()*0.6);
        addSubjectWindow.setPrefWidth(visualBound.getWidth()*0.8);
        addSubjectWindow.parentProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
                initSubjectCourse();
                initSubjectType();
            }else{
                //System.out.println("///");
                comb5.setItems(null);
            }
        });
        comb3.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){
                initSubjectChapter(newValue.getId());
                initSubjectCourseTarget(newValue.getId());
                selectCourseId=newValue.getId();
            }
        });
        comb3.setConverter(new StringConverter<CourseData>() {
            @Override
            public String toString(CourseData object) {
                return object.getName();
            }
            @Override
            public CourseData fromString(String string) {
                return null;
            }
        });
        comb4.setConverter(new StringConverter<CourseChapter>() {
            @Override
            public String toString(CourseChapter object) {
                return object.getContent();
            }
            @Override
            public CourseChapter fromString(String string) {
                return null;
            }
        });
        comb4.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){

                selectChapterId=newValue.getId();
            }
        });
        comb5.setConverter(new StringConverter<CourseTargetRecord>() {
            @Override
            public String toString(CourseTargetRecord object) {
                return object.getContent();
            }
            @Override
            public CourseTargetRecord fromString(String string) {
                return null;
            }
        });
        comb5.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){

                selectTargetId=newValue.getId();
            }
        });
        comb1.setConverter(new StringConverter<QuestionTypeRecord>() {
            @Override
            public String toString(QuestionTypeRecord object) {
                return object.getName();
            }
            @Override
            public QuestionTypeRecord fromString(String string) {
                return null;
            }
        });
        comb1.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if(newValue!=null){

                selectQueTypeId=newValue.getId();
            }
        });
    }

    private void initSubjectCourseTarget(String course_id) {
        subjectService.getCourseTargetRecord(new Callback<Result<List<CourseTargetRecord>>>() {
            @Override
            public void onResponse(Call<Result<List<CourseTargetRecord>>> call, Response<Result<List<CourseTargetRecord>>> response) {
                Platform.runLater(() -> {
                    assert response.body() != null;
                    if(response.body().getCode()==1&&response.body().getData().size()!=0&&response.body().getData()!=null){
                        courseTargetRecords= FXCollections.observableArrayList(response.body().getData());
                        comb5.setItems(courseTargetRecords);
                    }else{
                        comb5.setItems(null);
                        Platform.runLater(() -> {
                            Alert alert = new Alert(Alert.AlertType.INFORMATION, "该课程暂无课程目标信息");
                            alert.showAndWait();
                        });
                    }
                });
            }
            @Override
            public void onFailure(Call<Result<List<CourseTargetRecord>>> call, Throwable throwable) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION, "网络错误，请稍后再试");
                    alert.showAndWait();
                });
            }
        },course_id,dataStore.getTeacher_id(),dataStore.getToken());
    }

    private void initSubjectChapter(String course_id) {

        subjectService.getCourseChapterList(new Callback<Result<List<CourseChapter>>>() {
            @Override
            public void onResponse(Call<Result<List<CourseChapter>>> call, Response<Result<List<CourseChapter>>> response) {
                Platform.runLater(() -> {
                    assert response.body() != null;
                    if(response.body().getCode()==1&&response.body().getData()!=null){
                        courseChapters = FXCollections.observableArrayList(response.body().getData());
                        comb4.setItems(courseChapters);
                    }else{
                        Platform.runLater(() -> {
                            Alert alert = new Alert(Alert.AlertType.INFORMATION, "没有章节数据");
                            alert.showAndWait();
                        });
                    }
                });
            }

            @Override
            public void onFailure(Call<Result<List<CourseChapter>>> call, Throwable throwable) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION, "网络错误，请稍后再试");
                    alert.showAndWait();
                });
            }
        },course_id,dataStore.getTeacher_id(),dataStore.getToken());
    }

    private void initSubjectCourse() {
        subjectService.getCourseData(new Callback<Result<List<CourseData>>>() {
            @Override
            public void onResponse(Call<Result<List<CourseData>>> call, Response<Result<List<CourseData>>> response) {
                Platform.runLater(() -> {
                    assert response.body() != null;
                    if(response.body().getCode()==1&&response.body().getData()!=null){
                        com  = FXCollections.observableArrayList(response.body().getData());
                        comb3.setItems(com);
                        comb3.getSelectionModel().select(0);
                    }else{
                        Platform.runLater(() -> {
                            Alert alert = new Alert(Alert.AlertType.INFORMATION, "没有课程数据");
                            alert.showAndWait();
                        });
                    }
                });
            }
            @Override
            public void onFailure(Call<Result<List<CourseData>>> call, Throwable throwable) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.ERROR, "请求失败，请检查网络设置！");
                    alert.showAndWait();
                });
            }
        },dataStore.getTeacher_id(),dataStore.getToken());
    }

    private void initSubjectType() {
        subjectService.getQuesTypeList(new Callback<Result<List<QuestionTypeRecord>>>() {
            @Override
            public void onResponse(Call<Result<List<QuestionTypeRecord>>> call, Response<Result<List<QuestionTypeRecord>>> response) {
                Platform.runLater(() -> {
                    assert response.body() != null;
                    if(response.body().getCode()==1&&response.body().getData()!=null){
                        questionTypeRecords= FXCollections.observableArrayList(response.body().getData());
                        comb1.setItems(questionTypeRecords);
                    }else{
                        Platform.runLater(() -> {
                            Alert alert = new Alert(Alert.AlertType.INFORMATION, "没有题目类型数据");
                            alert.showAndWait();
                        });
                    }
                });
            }
            @Override
            public void onFailure(Call<Result<List<QuestionTypeRecord>>> call, Throwable throwable) {
                Platform.runLater(() -> {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION, "网络错误，请稍后再试");
                    alert.showAndWait();
                });
            }
        },dataStore.getToken(),dataStore.getTeacher_id());
    }

    public void addTrue(ActionEvent actionEvent) {
        if(trueTextAreas.size()<=8){
            TextArea textArea=new TextArea();
            textArea.setMaxHeight(200);
            trueVbox.getChildren().add(textArea);
            trueTextAreas.add(textArea);
        }
    }

    public void delFalse(ActionEvent actionEvent) {
        if(falseTextAreas.size()>0){
            falseVbox.getChildren().remove(falseTextAreas.size()-1);
            falseTextAreas.remove(falseTextAreas.size()-1);
        }
    }

    public void delTrue(ActionEvent actionEvent) {
        if(trueTextAreas.size()>0){
            trueVbox.getChildren().remove(trueTextAreas.size()-1);
            trueTextAreas.remove(trueTextAreas.size()-1);
        }
    }

    public void addFalse(ActionEvent actionEvent) {
        if(falseTextAreas.size()<=8){
           TextArea textArea=new TextArea();
           textArea.setMaxHeight(200);
            falseVbox.getChildren().add(textArea);
            falseTextAreas.add(textArea);
        }
    }

    public void setAddSubject(){

        SubjectDataInfo subjectDataInfo=new SubjectDataInfo();
        //获取单选按钮的值
        if(r1.isSelected()){
            subjectDataInfo.setDifficult(3);
        }else if(r2.isSelected()){
            subjectDataInfo.setDifficult(3);
        }else if(r3.isSelected()){
            subjectDataInfo.setDifficult(1);
        }
        subjectDataInfo.setContent(subjectContent.getText());
        subjectDataInfo.setResolve(subjectResolve.getText());
        subjectDataInfo.setChapter_id(selectChapterId);
        subjectDataInfo.setCourse_id(selectCourseId);
        subjectDataInfo.setKnowledgePointer(knowledgePoint.getText());
        subjectDataInfo.setCourseTargetId(selectTargetId);
        if(selectQueTypeId!=null){
            subjectDataInfo.setType_id(selectQueTypeId.toString());
        }
        List<AnswerObjRecoed> answerObjRecoeds=new ArrayList<>();
        if(trueTextAreas.size()!=0){
            for(TextArea a:trueTextAreas){
                answerObjRecoeds.add(new AnswerObjRecoed(null,a.getText(),true));
            }
        }
        if(falseTextAreas.size()!=0){
            for(TextArea a:falseTextAreas){
                answerObjRecoeds.add(new AnswerObjRecoed(null,a.getText(),false));
            }
        }
        subjectDataInfo.setAnswer(answerObjRecoeds);
        subjectStore.setAddSubject(subjectDataInfo);
    }
}
